<!--  -->
<template>
  <div class="allResource">
    <div class="allResourceBox">
      <div v-for="(item, index) in getUserRoleList" :key="index">
        <div class="roleTitle">
          <el-checkbox
            v-model="item.flag"
            @change="handleCheckAllChange(item.flag, item)"
            :indeterminate="item.isIndeterminate"
            >{{ item.name }}</el-checkbox
          >
        </div>
        <div class="roleContent">
          <el-checkbox-group v-model="item.children">
            <el-checkbox
              v-for="citem in getRoleList[index].children"
              :key="citem.id"
              :label="citem.id"
              @change="handleCheckedItemChange(item.id)"
              >{{ citem.name }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
      </div>
      <div class="btns">
        <el-button type="primary" size="default" @click="openChange"
          >保存</el-button
        >
        <el-button size="default" @click="empty">清空</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, computed } from "vue";
import * as http from "@/request";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
const route = useRoute();
const router = useRouter();
type IRoleList = {
  category: IRoleListResource[];
  resource: IRoleListResourceItem[];
  userResource: IRoleListResourceItem[];
};
const roleList = reactive<IRoleList>({
  category: [],
  resource: [],
  // 用户权限相关数据
  userResource: [],
});
const res1 = http.resourceCategoryListAll();
const res2 = http.resourceListAll();
const res3 = http.roleListResource(route.query.id as unknown as string);
try {
  let res = await Promise.all([res1, res2, res3]);
  roleList.category = res[0]["data"] as unknown as IRoleListResource[];
  roleList.resource = res[1]["data"] as unknown as IRoleListResourceItem[];
  roleList.userResource = res[2]["data"] as unknown as IRoleListResourceItem[];
} catch (error) {
  throw error;
}
const { category, resource, userResource } = toRefs(roleList);
const getRoleList = ref([] as IRoleAllResource[]);
const getUserRoleList = ref([] as IRoleUserList[]);
getRoleList.value = category.value.map((item) => {
  let newItem: IRoleAllResource = { ...item, children: [] };
  resource.value.forEach((citem) => {
    if (citem.categoryId === item.id) {
      newItem.children.push({
        id: citem.id,
        name: citem.name,
      });
    }
  });
  return newItem;
});
getUserRoleList.value = category.value.map((item, index) => {
  let newItem: IRoleUserList = {
    ...item,
    flag: false,
    isIndeterminate: false,
    children: [],
  };
  userResource.value.forEach((citem) => {
    if (citem.categoryId === item.id) {
      newItem.children.push(citem.id);
    }
  });
  if (newItem.children.length === getRoleList.value[index].children.length) {
    newItem.flag = true;
  }
  return newItem;
});
const handleCheckAllChange = (flag: boolean, citem: IRoleUserList) => {
  // console.log(flag);
  let allObj = getRoleList.value.find((item) => item.id === citem.id);
  // console.log(curObj);
  if (flag) {
    allObj!.children.forEach((item) => {
      if (!citem.children.includes(item.id)) {
        citem.children.push(item.id);
      }
    });
  } else {
    citem.children = [];
  }
  citem.isIndeterminate =
    citem.children.length > 0 &&
    citem.children.length < allObj!.children.length;
};
const handleCheckedItemChange = (id: number) => {
  let uerObj = getUserRoleList.value.find((item) => item.id === id);
  let allObj = getRoleList.value.find((item) => item.id === id);
  // checkAll.value = checkedCount === cities.length
  uerObj!.flag =
    uerObj?.children.length === allObj?.children.length ? true : false;
  uerObj!.isIndeterminate =
    uerObj!.children.length > 0 &&
    uerObj!.children.length < allObj!.children.length;
};

const empty = () => {
  getUserRoleList.value.forEach((item) => {
    item.children = [];
    item.flag = false;
    item.isIndeterminate = false;
  });
};
const openChange = () => {
  // console.log(getUserRoleList);
  const from = new FormData();
  from.append("roleId", route.query.id as string);
  let list: number[] = [];
  for (const item of getUserRoleList.value) {
    if (item.children.length === 0) continue;
    list = [...list, ...item.children];
  }
  from.append("resourceIds", list.join(","));
  // console.log(list);

  ElMessageBox.confirm("此操作将改变当前用户权限, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true,
  })
    .then(async () => {
      let res = await http.roleAllocResource(from);
      if (res.code === 200) {
        // 重新获取当前用户信息
        // unitPage();
        ElMessage({
          message: res.message,
          type: "success",
        });
        router.push("/ums/role");
      } else {
        ElMessage({
          message: res.message,
          type: "error",
        });
      }
    })
    .catch(() => {});
};
</script>
<style lang="scss" scoped>
.allResource {
  display: flex;
  flex-direction: column;
  padding: 10px 20px;
  box-sizing: border-box;
  width: 100%;
}
.allResourceBox {
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border: 1px solid #ebeef5;
}
.roleTitle {
  padding: 20px;
  background-color: #f2f6fc;
}
.roleContent {
  padding: 20px;
  :deep(.el-checkbox-group) {
    display: flex;
    flex-wrap: wrap;
    .el-checkbox {
      width: 33.333%;
      margin-right: 0;
      height: 20px;
    }
  }
}
.btns {
  text-align: center;
}
</style>
